package com.jtx.miaoah2.handler;

import com.jtx.miaoah2.Cache.HotCache;
import com.jtx.miaoah2.Common.RedisConstants;
import com.jtx.miaoah2.Mapper.SkGoodsMapper;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 季台星
 * @Date 2023 07 27 09 27
 */
@Order(2)
public class HotKeyInterceptor implements HandlerInterceptor {

    /**
     * 维护一个map集合记录热点数量访问量
     */
    public static ConcurrentHashMap<String,Integer> hotKeyCount = new ConcurrentHashMap<>();


    private final HotCache hotCache;

    public HotKeyInterceptor(HotCache hotCache) {
        this.hotCache = hotCache;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!request.getMethod().equals("GET")) {
            return true;
        }
        Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        if (pathVariables.isEmpty()){
            return true;
        }
        String id = (String) pathVariables.get("id");
        if (null == id){
            return true;
        }
        if (hotKeyCount.putIfAbsent(id, 0) != null){
            hotKeyCount.put(id, hotKeyCount.get(id) + 1);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
